#!coding=utf-8
'''
Created on 2014-5-23

@author: Administrator
'''
import time
from django.dispatch.dispatcher import receiver
from weixin.signals import wxsignal_subscribe_event,\
     wxsignal_location, wxsignal_text, wxsignal_click_event
from weixin.models import User
from weixin.send.service import send_text_msg, send_news_msg,\
    send_text_msg_count, send_img_msg
from nanjingzto.models import StoreInfo, postadmin
from weixin.api.common import calcDistance, getAccToken,\
    getWithParasDimensionalCode, upTmpImg
import urllib2
import json
import random
from django.core.exceptions import ObjectDoesNotExist
from weixin.send.msg import make_image_msg

@receiver(wxsignal_click_event)
def process_click_event(sender,**kwargs):
    if kwargs['msg']['EventKey']=="V1001_suggest":
        tmpopenid=kwargs['msg']['FromUserName']
        access_token=getAccToken()
        posturl = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=" + access_token   
        req=urllib2.urlopen(posturl)
        kfinfo=json.load(req);
        if len(kfinfo['kf_online_list'])==0:
            contval="您好，暂无客服在线，如果有需要帮助，请直接在微信留言。"
            send_text_msg(tmpopenid,contval);
            return {"MsgType":"transfer_customer_service"}
        else:
            contval="您好，微信客服正在为您服务，请问有什么需要帮助？"
            #指定wxid_9vc6zag3dj3811这个客服账号
            i=random.randint(0,len(kfinfo['kf_online_list'])-1)
            send_text_msg_count(tmpopenid,contval,kfinfo['kf_online_list'][i]["kf_account"].encode("utf-8"))
            
            return {"MsgType":"transfer_customer_service","TransInfo":kfinfo['kf_online_list'][i]["kf_account"].encode("utf-8")}
    elif kwargs['msg']['EventKey']=="V1001_USERCODE":
        tmpopenid=kwargs['msg']['FromUserName']
        try:
            tmpadmin=postadmin.objects.get(wx_id=tmpopenid)
            if tmpadmin.certid!="":
                name=tmpadmin.certid;
                if getWithParasDimensionalCode(name):
                    media_id=upTmpImg(name)
                    return make_image_msg(media_id)
                else:
                    contval="请联系微信平台运维人员"
                    send_text_msg(tmpopenid,contval);
            else:
                contval="请先至微信的员工入口登记身份证后，再提取二维码"
                send_text_msg(tmpopenid,contval);
        except ObjectDoesNotExist:
            contval="请先至微信公共号的员工入口登记注册后，再提取二维码"
            send_text_msg(tmpopenid,contval);
    
    else:
        return {"MsgType":"transfer_customer_service"}
@receiver(wxsignal_text)
def process_text_event(sender,**kwargs):
    return {"MsgType":"transfer_customer_service"}


@receiver(wxsignal_subscribe_event)
def process_subscribe_event(sender,**kwargs):
    print "wxsignal_subscribe_event"
    tmpopenid=kwargs['msg']['FromUserName']
    evtkey=kwargs['msg'].has_key('EventKey')
    if evtkey:
        userext=User.objects.filter(openid=tmpopenid)
        if userext.exists()==False:
            userext=User(openid=tmpopenid,subscribe_time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),referee=kwargs['msg']['EventKey'])
            userext.save();
        else:
            userext.update(referee=kwargs['msg']['EventKey']);
        contval="欢迎关注南京中通快递物流微信公共平台，我们将为您提供快件查询,在线下单等全方面的快递服务！"
        send_text_msg(tmpopenid,contval);
    else:
        userext=User.objects.filter(openid=tmpopenid)
        if userext.exists()==False:
            usertmp=User(openid=tmpopenid,subscribe_time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
            usertmp.save()
        print "222222222"
        contval="欢迎关注南京中通物流微信公共平台，我们将为您提供全方位的物流服务"
        send_text_msg(tmpopenid,contval);

@receiver(wxsignal_location)
def process_location_msg(sender,**kwargs):
    print "wxsignal_location_event" 
    tmpopenid=kwargs['msg']['FromUserName']
    Location_X=kwargs['msg']['Location_X']
    Location_Y=kwargs['msg']['Location_Y']
#     preci=kwargs['msg']['Precision']
#     print Location_X,Location_Y
    
    image_base = 'http://nanjing.wuxizto.com/img/'
    news_header = image_base + 'zto.jpg'
    
    url ="http://nanjing.wuxizto.com/storeinfo/?LX=%s&LY=%s"%(Location_Y,Location_X)
    send_news_msg(tmpopenid,"查看周围门店","点我查看",url,news_header);
    
        
#暂时不用
def getStroe(Location_X,Location_Y):
    qset=StoreInfo.objects.all();
    
    liststroe=[]
    listdis=[]
    
    for tmpset in qset:
        dis=calcDistance(float(Location_X),float(Location_Y),float(tmpset.latitude),float(tmpset.longitude))
        if dis < 10000 :
            liststroe.append(tmpset)
            listdis.append(dis)
#对拿到的商铺做排序，按距离近到远
#     if len(listdis)==0:
#         contval=u'附近暂无中通门店'
#         send_text_msg(tmpopenid,contval);
#     elif len(listdis)>1:
#         for i in range(len(listdis)-1): 
#             for j in range(i+1, len(listdis)): 
#                 if listdis[i]>listdis[j]: 
#                     listdis[i],listdis[j] = listdis[j],listdis[i] 
#                     liststroe[i],liststroe[j]=liststroe[j],liststroe[i]
#     else:
#         send_news_msg(tmpopenid,liststroe[0].store_name,liststroe[0].adress,url,news_header);

    